package com.bookseek.xreader.views.adapter;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.view.View;

import androidx.annotation.ColorInt;
import androidx.annotation.DimenRes;
import androidx.recyclerview.widget.RecyclerView;

public class LastItemNoDividerDecoration extends RecyclerView.ItemDecoration {
    private final Paint mPaint;
    private final int mDividerHeight;

    // 构造方法：传入分割线颜色和高度
    public LastItemNoDividerDecoration(Context context, @ColorInt int color, @DimenRes int heightRes) {
        mPaint = new Paint();
        mPaint.setColor(color);
        mPaint.setStyle(Paint.Style.FILL);
        mDividerHeight = context.getResources().getDimensionPixelSize(heightRes);
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);

        // 获取当前项的位置
        int position = parent.getChildAdapterPosition(view);
        // 获取总项数
        int itemCount = state.getItemCount();

        // 如果不是最后一项，就设置分割线的高度（这里是底部分割线）
        if (position != itemCount - 1) {
            outRect.bottom = mDividerHeight;
        } else {
            // 最后一项不设置分割线
            outRect.bottom = 0;
        }
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        super.onDraw(c, parent, state);
        int itemCount = state.getItemCount();

        // 遍历所有可见的item
        for (int i = 0; i < parent.getChildCount(); i++) {
            View view = parent.getChildAt(i);
            int position = parent.getChildAdapterPosition(view);

            // 如果是最后一项，不绘制分割线
            if (position == itemCount - 1) {
                continue;
            }

            // 计算分割线的位置（在item底部）
            float top = view.getBottom();
            float bottom = top + mDividerHeight;
            float left = parent.getPaddingLeft();
            float right = parent.getWidth() - parent.getPaddingRight();

            // 绘制分割线
            c.drawRect(left, top, right, bottom, mPaint);
        }
    }


}
